#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include <functional>

typedef std::function<std::string(const std::string&, const std::string&, uint16_t)> func_t;

std::string defaultIp = "0.0.0.0";
std::uint16_t defaultPort = 8080;

enum
{
    SOCKERT_FAIL = 1,
    BIND_FAIL,
};

Log lg;


class UdpServer
{

public:
    UdpServer(uint16_t port = defaultPort, std::string ip = defaultIp)
        : _port(port)
        , _ip(ip)
    {
    }

    void init()
    {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd == -1)
        {
            lg(Fatal, "sorket create fail, sockfd : %d", _sockfd);
            exit(SOCKERT_FAIL);
        }
        lg(Info, "sorket create success, sockfd : %d", _sockfd);

        // 绑定套接字
        struct sockaddr_in local;
        bzero(&local, sizeof(local));

        local.sin_family = AF_INET;        // 表明自己的类型
        local.sin_port = htons(_port);     // 大端
        // string -> uint36_t  // 网络序列
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        if(bind(_sockfd, (const struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno : %d, err string: %s", errno, strerror(errno));
            exit(BIND_FAIL);
        }
        lg(Info, "bind success, errno : %d, err string: %s", errno, strerror(errno));

    }

    void check_user(struct sockaddr_in& client, const std::string& clientip, const uint16_t& clientport)
    {
        if(_online_user.count(clientip) == 0)
        {
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
            _online_user.insert({ clientip, client });
        }
    }

    void broadcast(const std::string& clientip, const uint16_t& clientport, const std::string& info)
    {
        std::string ret = "[" + clientip + ":" + std::to_string(clientport) + "]# " + info;
        for(auto ch : _online_user)
        {
            sendto(_sockfd, ret.c_str(), ret.size(), 0, (struct sockaddr*)&(ch.second), sizeof(ch.second));
        }
    }

    void run(func_t func)
    {
        _isrunning = true;
        char inbuffer[1024];
        
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom error, errno : %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = '\0';
            //lg(Info, "recvfrom success, errno : %d, err string: %s", errno, strerror(errno));

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);

            check_user(client, clientip, clientport);

            broadcast(clientip, clientport, inbuffer);

            // std::string ret = func(inbuffer, clientip, clientport);
            // std::cout << ret << std::endl;

            //sendto(_sockfd, ret.c_str(), ret.size(), 0, (struct sockaddr*)&client, len);
        }
    }

    ~UdpServer()
    {

    }
    
private:
    std::string _ip;  // ip地址
    uint16_t _port;   // 端口号
    int _sockfd;       // 套接字文件描述符
    bool _isrunning;
    std::unordered_map<std::string, struct sockaddr_in> _online_user;
};